<template>
  <div class="check-input-container">
    <!-- 搜索栏 -->
    <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
      <el-input v-model="searchForm.checkNo" style="width: 240px; padding-right: 15px;" placeholder="请输入盘点单号" />
      <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable style="width: 200px; margin-right: 15px;">
        <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
      </el-select>
      <el-date-picker v-model="searchForm.startDate" type="date" placeholder="开始日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 150px; margin-right: 15px;" />
      <el-date-picker v-model="searchForm.endDate" type="date" placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 150px; margin-right: 15px;" />
      <el-icon @click="handleSearch()" style="margin-left: 20px; height: 25px; width: 25px;">
        <Search />
      </el-icon>
      <el-icon style="margin-left: 20px;" @click="resetSearch()">
        <Refresh />
      </el-icon>
      <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">新增盘点</el-button>
    </div>

    <!-- 盘点表格 -->
    <el-table :data="tableData" style="width: 100%" stripe border="true" v-loading="loading">
      <el-table-column label="序号" width="80px" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="checkNo" label="盘点单号" width="180" align="center" />
      <el-table-column prop="warehouseName" label="仓库名称" width="150" align="center" />
      <el-table-column prop="checkDate" label="盘点日期" width="150" align="center">
        <template #default="scope">{{ formatDateYMD(scope.row.checkDate) }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" align="center">
        <template #default="scope">
          <span v-if="scope.row.status == 0" style="color: gray;">草稿</span>
          <span v-if="scope.row.status == 1" style="color: green;">已审核</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="200" align="center" />
      <el-table-column label="操作" width="300px" fixed="right" align="center">
        <template #default="scope">
          <el-button type="primary" plain @click="viewCheckDetails(scope.row.id)">详情</el-button>
          <el-button type="warning" plain @click="showEditDialog(scope.row)" v-if="scope.row.status === 0">修改</el-button>
          <el-button type="success" plain @click="onAuditCheck(scope.row.id)" v-if="scope.row.status === 0">审核</el-button>
          <el-button type="danger" plain @click="onDeleteCheck(scope.row.id)" v-if="scope.row.status === 0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[3, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑盘点' : '新增盘点'" width="1150px" :before-close="handleDialogClose" :close-on-click-modal="false" style="left: 90px">
      <el-form :model="inventoryCheck" :rules="rules" ref="formRef" label-width="120px" style="padding: 15px 0;">
        <el-form-item label="盘点单号" prop="checkNo" v-if="isEdit">
          <el-input v-model="inventoryCheck.checkNo" disabled placeholder="系统自动生成" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select v-model="inventoryCheck.warehouseId" placeholder="请选择仓库" clearable style="width: 100%" @change="onWarehouseChange">
            <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点日期" prop="checkDate">
          <el-date-picker v-model="inventoryCheck.checkDate" type="date" placeholder="请选择盘点日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>
        <el-form-item label="盘点状态" prop="status" v-if="isEdit">
          <el-select v-model="inventoryCheck.status" placeholder="请选择盘点状态" style="width: 100%">
            <el-option label="草稿" :value="0" />
            <el-option label="已审核" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="inventoryCheck.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>

        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <div class="items-container">
            <div class="items-header">
              <h4>盘点商品明细</h4>
              <el-button type="primary" size="small" @click="addItem">添加商品</el-button>
            </div>
            <el-table :data="inventoryCheck.items || []" style="width: 100%" stripe border="true">
              <el-table-column label="序号" width="60px" align="center">
                <template #default="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column label="产品名称" width="200px">
                <template #default="scope">
                  <div v-if="isEdit && scope.row.productId && scope.row.productName">
                    <span>{{ scope.row.productName }}</span>
                    <el-button type="text" size="small" @click="editProduct(scope.row)" style="margin-left: 10px;">修改</el-button>
                  </div>
                  <el-select v-else v-model="scope.row.productId" placeholder="请选择产品" @change="onProductChange(scope.row)">
                    <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="系统数量" width="120px" align="center">
                <template #default="scope">
                  <span>{{ scope.row.quantity || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="实际数量" width="150px">
                <template #default="scope">
                  <el-input-number v-model="scope.row.actualQuantity" :min="0" :precision="2" :step="1" @change="calculateDifference(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="差异数量" width="120px" align="center">
                <template #default="scope">
                  <span :style="{ color: getDifferenceColor(scope.row.difference) }">
                    {{ scope.row.difference || 0 }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="备注" width="150px">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" placeholder="备注" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100px" align="center">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose" size="default">取消</el-button>
          <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 盘点详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="盘点详情" width="800px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
      <div v-if="currentCheck" class="check-detail">
        <div class="detail-header">
          <p><span class="label">盘点单号：</span>{{ currentCheck.checkNo }}</p>
          <p><span class="label">仓库名称：</span>{{ currentCheck.warehouseName }}</p>
          <p><span class="label">盘点日期：</span>{{ formatDateYMD(currentCheck.checkDate) }}</p>
          <p><span class="label">盘点状态：</span>
            <span v-if="currentCheck.status == 0" style="color: gray;">草稿</span>
            <span v-if="currentCheck.status == 1" style="color: green;">已审核</span>
          </p>
          <p><span class="label">备注：</span>{{ currentCheck.remark }}</p>
        </div>

        <div class="detail-items">
          <h3>商品明细</h3>
          <el-table :data="currentCheck.items || []" style="width: 100%" stripe border="true">
            <el-table-column label="序号" width="80px" align="center">
              <template #default="scope">{{ scope.$index + 1 }}</template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" width="180" align="center" />
            <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
            <el-table-column prop="quantity" label="系统数量" width="120" align="center" />
            <el-table-column prop="actualQuantity" label="实际数量" width="120" align="center" />
            <el-table-column prop="difference" label="差异数量" width="120" align="center">
              <template #default="scope">
                <span :style="{ color: getDifferenceColor(scope.row.difference) }">
                  {{ scope.row.difference || 0 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="120" align="center" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getWarehouseList, getProductList } from '@/api/warehouse/warehouse'
import { 
  getInventoryCheckPage,
  getInventoryCheckWithDetails,
  createInventoryCheck,
  updateInventoryCheck,
  deleteInventoryCheck,
  auditInventoryCheck,
  getProductStockQuantity
} from '@/api/check/check'

export default {
  name: 'CheckInput',
  setup() {
    // 工具函数：日期格式化仅显示 YYYY-MM-DD
    function formatDateYMD(value) {
      if (!value) return ''
      if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) return value
      if (typeof value === 'string') {
        const m = value.match(/^(\d{4}-\d{2}-\d{2})/)
        if (m) return m[1]
      }
      try {
        const d = new Date(value)
        if (!isNaN(d.getTime())) {
          const y = d.getFullYear()
          const mm = String(d.getMonth() + 1).padStart(2, '0')
          const dd = String(d.getDate()).padStart(2, '0')
          return `${y}-${mm}-${dd}`
        }
      } catch (_) {}
      return String(value)
    }

    // 响应式数据
    const loading = ref(false)
    const dialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const isEdit = ref(false)
    const formRef = ref(null)
    const currentCheck = ref(null)

    // 搜索表单
    const searchForm = reactive({
      checkNo: '',
      warehouseId: null,
      startDate: '',
      endDate: ''
    })

    // 分页
    const pagination = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0
    })

    // 盘点数据
    const inventoryCheck = ref({
      id: null,
      checkNo: '',
      warehouseId: null,
      checkDate: '',
      status: 0,
      remark: '',
      items: []
    })

    // 列表数据
    const tableData = ref([])
    const warehouseList = ref([])
    const productList = ref([])

    // 表单验证规则
    const rules = {
      warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
      checkDate: [{ required: true, message: '请选择盘点日期', trigger: 'change' }]
    }

    // 计算属性
    const dialogTitle = computed(() => (isEdit.value ? '编辑盘点' : '新增盘点'))

    // 加载列表（旧的模拟方法，保留为备选，不再使用）
    const loadDataMock = async () => {
      loading.value = true
      try {
        // TODO: 调用后端API
        // const params = {
        //   pageNum: pagination.pageNum,
        //   pageSize: pagination.pageSize,
        //   checkNo: searchForm.checkNo,
        //   warehouseId: searchForm.warehouseId,
        //   startDate: searchForm.startDate,
        //   endDate: searchForm.endDate
        // }
        // const page = await getInventoryCheckPage(params)
        // tableData.value = Array.isArray(page?.records) ? page.records : []
        // pagination.total = Number(page?.total) || tableData.value.length || 0
        
        // 模拟数据
        tableData.value = [
          {
            id: 1,
            checkNo: 'PD001',
            warehouseName: '主仓库',
            checkDate: '2025-01-15',
            status: 0,
            remark: '月度盘点'
          }
        ]
        pagination.total = tableData.value.length
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    const loadWarehouseList = async () => {
      try {
        const data = await getWarehouseList()
        warehouseList.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : [])
      } catch (error) {
        console.error('加载仓库列表失败:', error)
      }
    }

    const loadProductList = async () => {
      try {
        const data = await getProductList()
        productList.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : [])
      } catch (error) {
        console.error('加载商品列表失败:', error)
      }
    }

    const handleSearch = () => {
      pagination.pageNum = 1
      loadData()
    }

    const resetSearch = () => {
      Object.assign(searchForm, { checkNo: '', warehouseId: null, startDate: '', endDate: '' })
      pagination.pageNum = 1
      loadData()
    }

    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadData()
    }

    const handleCurrentChange = (val) => {
      pagination.pageNum = val
      loadData()
    }

    const showAddDialog = () => {
      isEdit.value = false
      inventoryCheck.value = {
        id: null,
        checkNo: '',
        warehouseId: null,
        checkDate: new Date().toISOString().split('T')[0],
        status: 0,
        remark: '',
        items: []
      }
      dialogVisible.value = true
      if (formRef.value) formRef.value.resetFields()
    }

    const showEditDialog = async (row) => {
      isEdit.value = true
      dialogVisible.value = true
      try {
        const data = await getInventoryCheckWithDetails(row.id)
        // 计算差异字段供展示
        if (Array.isArray(data?.items)) {
          data.items = data.items.map(it => ({
            ...it,
            difference: Number(((Number(it.actualQuantity)||0) - (Number(it.quantity)||0)).toFixed(2))
          }))
        }
        inventoryCheck.value = data || { ...row, items: [] }
      } catch (error) {
        console.error('获取盘点详情失败:', error)
        ElMessage.error('获取盘点详情失败')
        inventoryCheck.value = { ...row, items: [] }
      }
    }

    const handleDialogClose = () => {
      dialogVisible.value = false
      inventoryCheck.value = {
        id: null,
        checkNo: '',
        warehouseId: null,
        checkDate: '',
        status: 0,
        remark: '',
        items: []
      }
      if (formRef.value) formRef.value.resetFields()
    }

    const addItem = () => {
      if (!inventoryCheck.value.items) inventoryCheck.value.items = []
      inventoryCheck.value.items.push({
        productId: null,
        productName: null,
        productCode: null,
        quantity: 0,         // 账面数量
        actualQuantity: 0,   // 实盘数量
        difference: 0,
        remark: ''
      })
    }

    const removeItem = (index) => {
      inventoryCheck.value.items.splice(index, 1)
    }

    const editProduct = (item) => {
      item.productId = null
      item.productName = null
      item.productCode = null
    }

    const onProductChange = async (item) => {
      const product = productList.value.find(p => p.id === item.productId)
      if (product) {
        item.productName = product.name
        item.productCode = product.barcode || product.code
      }
      
      // 获取系统库存数量
      if (item.productId && inventoryCheck.value.warehouseId) {
        try {
          const stockQuantity = await getProductStockQuantity(item.productId, inventoryCheck.value.warehouseId)
          item.quantity = stockQuantity
        } catch (error) {
          console.error('获取库存数量失败:', error)
          item.quantity = 0
        }
      }
      
      calculateDifference(item)
    }

    const onWarehouseChange = async () => {
      // 切换仓库时刷新所有商品的系统库存数量
      if (inventoryCheck.value.items && inventoryCheck.value.items.length > 0) {
        for (const item of inventoryCheck.value.items) {
          if (item.productId) {
            try {
              const stockQuantity = await getProductStockQuantity(item.productId, inventoryCheck.value.warehouseId)
              item.quantity = stockQuantity
              calculateDifference(item)
            } catch (error) {
              console.error('获取库存数量失败:', error)
              item.quantity = 0
              calculateDifference(item)
            }
          }
        }
      }
    }

    const calculateDifference = (item) => {
      const qty = Number(item.quantity) || 0
      const act = Number(item.actualQuantity) || 0
      item.difference = Number((act - qty).toFixed(2))
    }

    const getDifferenceColor = (value) => {
      const num = Number(value) || 0
      if (num > 0) return 'green'
      if (num < 0) return 'red'
      return 'inherit'
    }

    // 接口导入见顶部 import

    // 加载列表（调用后端）
    const loadDataReal = async () => {
      const params = {
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
        checkNo: searchForm.checkNo,
        warehouseId: searchForm.warehouseId,
        startDate: searchForm.startDate,
        endDate: searchForm.endDate
      }
      const page = await getInventoryCheckPage(params)
      tableData.value = Array.isArray(page?.records) ? page.records : []
      pagination.total = Number(page?.total) || tableData.value.length || 0
    }

    // 用真实接口替换模拟
    const loadData = async () => {
      loading.value = true
      try {
        await loadDataReal()
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    const submitForm = async () => {
      if (!formRef.value) return
      try {
        await formRef.value.validate()
        if (!inventoryCheck.value.items || inventoryCheck.value.items.length === 0) {
          ElMessage.warning('请至少添加一个商品')
          return
        }

        const convertItems = (items) =>
          items.map(it => ({
            id: it.id,
            productId: it.productId,
            quantity: it.quantity,
            actualQuantity: it.actualQuantity,
            remark: it.remark
          }))

        if (isEdit.value) {
          const updateData = { ...inventoryCheck.value }
          updateData.items = convertItems(updateData.items)
          if (updateData.checkDate) updateData.checkDate = formatDateYMD(updateData.checkDate)
          const updated = await updateInventoryCheck(updateData)
          ElMessage.success('更新成功')
          // 同步到表格行
          if (updated) {
            const idx = tableData.value.findIndex(x => x.id === updated.id)
            if (idx !== -1) tableData.value[idx] = { ...tableData.value[idx], ...updated }
          }
        } else {
          const createData = { ...inventoryCheck.value }
          delete createData.id
          delete createData.checkNo
          createData.items = convertItems(createData.items).map(it => ({ id: undefined, ...it }))
          if (createData.checkDate) createData.checkDate = formatDateYMD(createData.checkDate)
          await createInventoryCheck(createData)
          ElMessage.success('创建成功')
        }

        dialogVisible.value = false
        await loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('提交失败:', error)
          ElMessage.error('提交失败')
        }
      }
    }

    const onDeleteCheck = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个盘点单吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        await deleteInventoryCheck(id)
        ElMessage.success('删除成功')
        await loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    const onAuditCheck = async (id) => {
      try {
        await ElMessageBox.confirm('确定要审核该盘点单吗？审核后将根据差异调整库存。', '审核确认', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        await auditInventoryCheck(id)
        ElMessage.success('审核成功，库存已调整')
        await loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审核失败:', error)
          ElMessage.error('审核失败')
        }
      }
    }

    const viewCheckDetails = async (id) => {
      try {
        const data = await getInventoryCheckWithDetails(id)
        if (Array.isArray(data?.items)) {
          data.items = data.items.map(it => ({
            ...it,
            difference: Number(((Number(it.actualQuantity)||0) - (Number(it.quantity)||0)).toFixed(2))
          }))
        }
        currentCheck.value = data || null
        detailDialogVisible.value = true
      } catch (error) {
        console.error('获取盘点详情失败:', error)
        ElMessage.error('获取盘点详情失败')
      }
    }

    const handleDetailDialogClose = () => {
      detailDialogVisible.value = false
      currentCheck.value = null
    }

    onMounted(() => {
      loadData()
      loadWarehouseList()
      loadProductList()
    })

    return {
      // 数据
      loading,
      dialogVisible,
      detailDialogVisible,
      isEdit,
      formRef,
      currentCheck,
      searchForm,
      pagination,
      inventoryCheck,
      tableData,
      warehouseList,
      productList,
      rules,
      dialogTitle,
      // 方法
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      showAddDialog,
      showEditDialog,
      handleDialogClose,
      addItem,
      removeItem,
      editProduct,
      onProductChange,
      onWarehouseChange,
      calculateDifference,
      getDifferenceColor,
      submitForm,
      onDeleteCheck,
      onAuditCheck,
      viewCheckDetails,
      handleDetailDialogClose,
      formatDateYMD
    }
  }
}
</script>

<style scoped>
.check-input-container {
  padding: 20px;
}

.search-bar {
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar .el-input,
.search-bar .el-select,
.search-bar .el-date-picker {
  margin-right: 15px;
}

.search-bar .el-button {
  margin-left: 15px;
}

.items-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
}

.items-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.check-detail .detail-header p { margin: 8px 0; }
.label { font-weight: bold; display: inline-block; width: 100px; }
</style>